package no.ntnu.fp.handlers;

import java.io.IOException;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.AcceptNoticeMessage;
import no.ntnu.fp.messages.impl.MeetingAddedMessage;
import no.ntnu.fp.messages.impl.MeetingUpdatedMessage;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.model.Notice;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.NoticeService;

public class AcceptNoticeHandler implements Handler {
	private final NoticeService noticeService;

	public AcceptNoticeHandler(NoticeService noticeService) {
		this.noticeService = noticeService;
	}

	@Override
	public void handleMessage(Message message) {
		AcceptNoticeMessage acceptNoticeMessage = (AcceptNoticeMessage) message;
		Notice notice = acceptNoticeMessage.getNotice();

		Meeting updatedMeeting = noticeService.acceptNotice(notice);
		if(!updatedMeeting.isCancelled()){
			switch (notice.getNoticeType()) {
			case NewMeeting: 
				message = new MeetingAddedMessage(updatedMeeting);
				break;
			case ChangedMeeting:
				message = new MeetingUpdatedMessage(updatedMeeting);
				break;
			default:
				throw new IllegalArgumentException(
						"Cannot accept notice with notice type " + notice.getNoticeType());
			}

			Connection connection = ReceiveWorker.getThreadLocalConnection();
			try {
				connection.send(message.toString());
			} catch (IOException e) {
				throw new NetworkException(String.format(
						"Could not send notice acception acknowledgement for notice %s"
						, notice), e);
			}
		}
	}
}
